 /** @type {HTMLCanvasElement} */
 let canvas = document.querySelector('#canvas')
 /** @type {CanvasRenderingContext2D} */
 let ctx = canvas.getContext('2d')

 const audio = document.querySelector('audio')


 let screenWidth = document.body.clientWidth
 let screenHeight = window.innerHeight

 function init(){
    canvas.width = screenWidth
    canvas.height = screenHeight / 2 * devicePixelRatio
 }

 init()
 let isInit = false
var reqs = null

var getRandomColor = function(){
    return '#'+Math.floor(Math.random()*16777215).toString(16); 
  }
var color = getRandomColor()
 function draw(){
    reqs =  requestAnimationFrame(draw)
    if(!isInit) return
    const {width,height} = canvas
    ctx.clearRect(0,0,width,height)
    analyser.getByteFrequencyData(dataArray)
    // console.log(dataArray);
    const len = dataArray.length / 1.2
    let barWidth = width / len / 2 // 每一根条的宽度
    for(let i = 0;i < len;i++) {
        const data = dataArray[i] // 因为是每个是uni8所以每个值都是<256
        const barHeight = data / 255 * height
        ctx.fillStyle = color
        let x1 = width / 2 + (barWidth * i)
        // let x1 = barWidth * i
        let y1 = height - barHeight
        let x2 = width / 2 - (barWidth * (i+1))
        let y2 = height - barHeight
        ctx.fillRect(x1,y1,barWidth - 5,barHeight)
        ctx.fillRect(x2,y2,barWidth - 5,barHeight)
    }
 }

 let analyser,dataArray
 audio.onplay = function(){
    console.log('is',audio.paused);
    // 播放函数 如果初始化了则不进行初始化 如果没有初始化则进行初始化动画
    if(isInit) return
    const audCtx = new AudioContext()
    const source = audCtx.createMediaElementSource(audio) // 创建音频源节点
    analyser = audCtx.createAnalyser()
    analyser.fftSize = 512
    // 创建数组用来接收分析器接待你的分析的数据
    dataArray = new Uint8Array(analyser.frequencyBinCount)
    source.connect(analyser)
    analyser.connect(audCtx.destination)
    isInit = true
    draw()
 }

//  audio.onpause= function(){
//     if(audio.paused) {
//         window.cancelAnimationFrame(reqs)
//     }
//     console.log('audito',audio.paused);
//   }